﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;

namespace Falafel.Controls.Dialogs
{
    static public class DialogUtils
    {
        static public List<T> GetDescendants<T>(this FrameworkElement parent, string ignore = null) where T : FrameworkElement
        {
            List<T> children = new List<T>();
            int count = VisualTreeHelper.GetChildrenCount(parent);

            if (count > 0)
            {
                int i = 0;
                while (i < count)
                {
                    FrameworkElement child = (FrameworkElement)VisualTreeHelper.GetChild(parent, i);

                    if (child is T)
                    {
                        if ((ignore == null) || (!child.Name.StartsWith(ignore)))
                        {
                            children.Add((T)child);
                        }
                    }
         
                    children.AddRange(child.GetDescendants<T>(ignore));
                    System.Math.Max(System.Threading.Interlocked.Increment(ref i), i - 1);
                }

                return children;
            }
            
            return new List<T>();
        }
    }
}